using System.Collections.Generic;
using System.Linq;
using CxRomos.Core.Domain;
using CxRomos.Core.Domain.Entities;
using StructureMap;

namespace CxRomos.Core.DataAccess.Implementation {
    [Pluggable("Default")]
    public class PermissionRepository : RepositoryBase, IPermissionRepository {
        public List<Permission> GetAllPermissions() {
            var permissions = (from p in Context.Permissions
                               select p).ToList();

            return permissions;
        }

        public List<Permission> GetPermissionsByAccountId(int accountId) {
            var permissions = (from p in Context.Permissions
                               join ap in Context.AccountPermissions on p.PermissionId equals ap.Permission.PermissionId
                               join a in Context.Accounts on ap.AccountId equals a.AccountId
                               where a.AccountId == accountId
                               select p).ToList();

            return permissions;
        }

        public List<Permission> GetPermissionByName(string name) {
            var permissions = (from p in Context.Permissions
                               where p.Name == name
                               select p).ToList();

            return permissions;
        }

        public List<Permission> GetPermissionById(int permissionId) {
            var permissions = (from p in Context.Permissions
                               where p.PermissionId == permissionId
                               select p).ToList();

            return permissions;
        }

        public void SavePermission(Permission permission) {
            BeginTransaction();
            NHibernateSession.SaveOrUpdate(permission);
        }

        public void SavePermissions(List<Permission> permissions) {
            BeginTransaction();
            foreach (var permission in permissions) {
                NHibernateSession.SaveOrUpdate(permission);
            }
        }

        public void DeletePermission(Permission permission) {
            BeginTransaction();
            NHibernateSession.Delete(permission);
        }
    }
}